import { login, logout } from '@/api/user'
import { getToken, setToken, removeToken, getUserInfo, setUserInfo, removeUserInfo } from '@/utils/auth'
import router, { resetRouter } from '@/router'

const state = {
  token: getToken(),
  name: '',
  avatar: '',
  introduction: '',
  userInfo: getUserInfo()
}

const mutations = {
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_DOMAINID: (state, domainId) => {
    state.domainId = domainId
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_USERINFO: (state, userInfo) => {
    state.userInfo = userInfo
  }
}

const actions = {
  // user login
  login({ commit }, userInfo) {
    const { username, password, domainCode } = userInfo
    return new Promise((resolve, reject) => {
      login({
        username: username.trim(),
        password: password,
        domainCode: domainCode
      })
        .then(response => {
          const { data } = response
          const { user } = data
          const roles = []
          if (user.superAdminStatus) {
            roles.push('superAdmin')
          } else if (user.adminStatus) {
            roles.push('admin')
          }
          if (roles.length <= 0) {
            roles.push('visitor')
          }
          const userInfo = {
            roles,
            username: user.username,
            domainId: user.domainCode,
            domainName: user.domainName,
            projectId: user.projectId,
            projectName: user.projectName,
            id: user.id
          }
          commit('SET_TOKEN', data.accessToken)
          commit('SET_USERINFO', userInfo)
          setToken(data.accessToken)
          setUserInfo(JSON.stringify(userInfo))
          resolve(data)
        })
        .catch(error => {
          reject(error)
        })
    })
  },

  updateUser({ commit, state }, newUserInfo) {
    const { userInfo } = state
    Object.assign(userInfo, newUserInfo)
    commit('SET_USERINFO', userInfo)
  },

  // user logout
  logout({ commit, state, dispatch }) {
    return new Promise((resolve, reject) => {
      logout().then(() => {
        commit('SET_TOKEN', '')
        commit('SET_USERINFO', '')
        removeToken()
        resetRouter()

        // reset visited views and cached views
        // to fixed https://github.com/PanJiaChen/vue-element-admin/issues/2485
        dispatch('tagsView/delAllViews', null, { root: true })
        dispatch('permission/delRoutes', [], { root: true })

        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      commit('SET_TOKEN', '')
      commit('SET_USERINFO', '')
      removeToken()
      removeUserInfo()
      resolve()
    })
  },

  // dynamically modify permissions
  async changeRoles({ commit, dispatch }, role) {
    const token = role + '-token'

    commit('SET_TOKEN', token)
    setToken(token)

    const { roles } = getUserInfo()

    resetRouter()

    // generate accessible routes map based on roles
    const accessRoutes = await dispatch('permission/generateRoutes', roles, { root: true })
    // dynamically add accessible routes
    router.addRoutes(accessRoutes)

    // reset visited views and cached views
    dispatch('tagsView/delAllViews', null, { root: true })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
